package com.ihelp.rest.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ihelp.rest.base.po.SpecialUrl;
import com.ihelp.rest.utils.SessionUtils;
import com.ihelp.rest.utils.SpringContextUtil;

/**
 * 用户登陆Session管理
*      
* 类名称：UserFilter   
* 类描述：     
* 创建时间：2013-3-18 下午08:22:29    
* 备注：   
* @version
 */
public class UserFilter implements Filter{
	
	private SpecialUrl specialUrl;

	/**
	 * 销毁
	 */
	public void destroy() {
		
	}

	/**
	 * 过滤
	 */
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;  
		HttpServletResponse response = (HttpServletResponse) res; 
		//不合法跳转登陆页面
		if(!this.checkUserSession(request)){
			response.sendRedirect(request.getContextPath() + "/login.jsp" );
			return;
		}
		chain.doFilter(request, response);
	}
	
	/**
	 * 核对Session
	 * @param url
	 * @return
	 */
	private boolean checkUserSession(HttpServletRequest request){
		String requestUrl = request.getRequestURI(); 
		if(requestUrl.indexOf("login.do") > -1){
			return true;
		}
		else if(specialUrl.getUrls().contains(requestUrl)){
			return true;
		}
		else if(SessionUtils.getUser(request) != null){
			return true;
		}
		return false;
	}

	/**
	 * 初始化
	 */
	public void init(FilterConfig arg0) throws ServletException {
		this.specialUrl = SpringContextUtil.getBean("specialUrl");
	}

}
